package com.baizhi.service.impl;

import com.baizhi.dao.CmfzArticleDao;
import com.baizhi.entity.CmfzArticle;
import com.baizhi.service.LuceneService;
import com.baizhi.util.LuceneUtil;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/4/15 0015.
 */
@Service
public class LuceneServiceImpl implements LuceneService {
    @Autowired
    private CmfzArticleDao cmfzArticleDao;
    private Logger logger=LoggerFactory.getLogger(LuceneServiceImpl.class);

    @Override
    public void addIndexs() {
        List<CmfzArticle> cmfzArticles = cmfzArticleDao.selectList(null);
        for (CmfzArticle cmfzArticle : cmfzArticles) {
            org.apache.lucene.document.Document document = new org.apache.lucene.document.Document();
            /*需要将int转换成String类型的*/
            document.add(new TextField("articleId", cmfzArticle.getArticleId().toString(), Field.Store.YES));
            document.add(new TextField("articleName", cmfzArticle.getArticleName(), Field.Store.YES));
            document.add(new StringField("articleImage", cmfzArticle.getArticleImage(), Field.Store.YES));
            document.add(new TextField("articleContent", cmfzArticle.getArticleContent(), Field.Store.YES));
            IndexWriter indexWriter = LuceneUtil.getIndexWriter();
            try {
                indexWriter.addDocument(document);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                LuceneUtil.commit(indexWriter);
            }
        }
    }

    @Override
    public boolean addIndexOne(CmfzArticle cmfzArticle) {
        org.apache.lucene.document.Document document = new org.apache.lucene.document.Document();
        document.add(new IntField("articleId", cmfzArticle.getArticleId(), Field.Store.YES));
        document.add(new TextField("articleName", cmfzArticle.getArticleName(), Field.Store.YES));
        document.add(new TextField("articleContent", cmfzArticle.getArticleContent(), Field.Store.YES));
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.addDocument(document);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }


    }

    @Override
    public boolean deleteAllIndex() {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteAll();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }

    }

    @Override
    public boolean deleteOne(CmfzArticle cmfzArticle) {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            indexWriter.deleteDocuments(new Term("articleId", cmfzArticle.getArticleId().toString()));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }

    }

    @Override
    public boolean updateOne(CmfzArticle cmfzArticle) throws IOException {
        IndexWriter indexWriter = LuceneUtil.getIndexWriter();
        try {
            Document document = new Document();
            document.add(new TextField("articleId", cmfzArticle.getArticleId().toString(), Field.Store.YES));
            document.add(new TextField("articleName", "没有资格跟随上师", Field.Store.YES));
            document.add(new StringField("articleImage", cmfzArticle.getArticleImage(), Field.Store.YES));
            document.add(new TextField("guruId", cmfzArticle.getGuruId().toString(), Field.Store.YES));
            document.add(new TextField("articleDate", cmfzArticle.getArticleDate().toString(), Field.Store.YES));
            document.add(new TextField("articleState", cmfzArticle.getArticleState().toString(), Field.Store.YES));

            indexWriter.updateDocument(new Term("articleId", cmfzArticle.getArticleId().toString()), document);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            LuceneUtil.commit(indexWriter);
        }
    }

    @Override
    public List<CmfzArticle> queryByKeyword(String keyword) throws IOException, InvalidTokenOffsetsException {
        ArrayList<CmfzArticle> cmfzArticles = new ArrayList<>();
        /*定义高亮规则*/
        SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter("<font color='red'>"," </font>");

        /*生成新的查询条件对象*/
        Query query = LuceneUtil.getQuery(keyword);
        QueryScorer queryScorer = new QueryScorer(query);

        /*生成高亮器*/
        Highlighter highlighter = new Highlighter(htmlFormatter,queryScorer);
        /*读取索引库，获取流对象*/

        IndexSearcher indexSearcher = LuceneUtil.getIndexSearcher();
        TopDocs topDocs = null;
        try {
            topDocs = indexSearcher.search(query, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            int doc = scoreDoc.doc;
            Document document = null;
            try {
                document = indexSearcher.doc(doc);
            } catch (IOException e) {
                e.printStackTrace();
            }
            CmfzArticle cmfzArticle = new CmfzArticle();
            cmfzArticle.setArticleId(Integer.parseInt(document.get("articleId")));
            cmfzArticle.setArticleName(highlighter.getBestFragment(LuceneUtil.analyzer,"articleName",document.get("articleName")));
            cmfzArticle.setArticleImage(document.get("articleImage"));
            logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@{}",document.get("articleContent"));
            cmfzArticle.setArticleContent(document.get("articleContent"));
            /*cmfzArticle.setArticleContent(highlighter.getBestFragment(LuceneUtil.analyzer,"articleContent",document.get("articleContent")));*/
            cmfzArticles.add(cmfzArticle);
        }
        return cmfzArticles;
    }

    @Override
    public boolean resetIndexDB() {
        try {
            deleteAllIndex();
            addIndexs();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
